package com.orange.base.component.biztool.simulateddata.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.orange.base.component.biztool.simulateddata.service.SimulatedDataEnum;
import com.orange.base.component.biztool.simulateddata.service.SimulatedDataParam;

/**
 * yyyy-MM-dd
 *
 * @author biankudingcha
 * @date: 2022-08-24
 * @since 0.5.0
 */
public class DateStrategy extends DateTimeStrategy {

    @Override
    public Object getValue(SimulatedDataParam param) {
        return generate(param);
    }

    public static String generate(SimulatedDataParam param) {
        String min = toStr(param.getMin());
        String max = toStr(param.getMax());
        try {
            if (min.length() == 10 && max.length() == 10) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                Date start = format.parse(min);// 构造开始日期
                Date end = format.parse(max);// 构造结束日期
                if (start.getTime() >= end.getTime()) {
                    return null;
                }
                long date = random(start.getTime(), end.getTime());
                Date newDate = new Date(date);
                return format.format(newDate);
            } else {
                return getYear(null, null) + "-" + getMonth() + "-" + getDay();
            }
        } catch (Exception e) {

        }
        return null;
    }

    public String getBeanId() {
        return getType();
    }

    public String getType() {
        return SimulatedDataEnum.DATE.getName();
    }

    public String getCaption() {
        return SimulatedDataEnum.DATE.getCaption();
    }

    private static long random(long begin, long end) {
        long rtn = begin + (long) (Math.random() * (end - begin));
        // 如果返回的是开始时间和结束时间，则递归调用本函数查找随机值
        if (rtn == begin || rtn == end) {
            return random(begin, end);
        }
        return rtn;
    }

}
